from flask import Flask, request
from components.nacos.connector import SERVICE_PORT
from components.nacos.service import proxy_service
from initiate import register_heartbeat_to_nacos, register_middleware

app = Flask(__name__)


@app.route('/<service_name>/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def proxy(service_name, path):
    # 转代理
    response = proxy_service(service_name, path, request)
    # print(response)
    if type(response) == dict:
        return response
    # 错误处理
    if response.status_code != 200:
        return {'status': response.status_code, 'message': response.text}
    return response.content


if __name__ == '__main__':
    register_middleware(app)
    register_heartbeat_to_nacos()
    app.run(port=SERVICE_PORT, debug=True)
